<?php 
header("Content-Type:text/html;charset=UTF-8");
error_reporting(3);
date_default_timezone_set('PRC');//Africa/Lubumbashi//PRC
class db_connect{
    private $host;
    private $db_name;
    private $user;
    private $pwd;
    private $charset;
    private $con;
    public $tab;
    public $field='*';
    public $where;
    public $group;
    public $order;

    public function __construct($host='localhost',$db_name='',$user='',$pwd='',$charset='utf8'){
        $this->host=$host;
        $this->db_name=$db_name;
        $this->user=$user;
        $this->pwd=$pwd;
        $this->charset=$charset;
        $this->connect();
    }

    public function connect(){
        $this->con=@mysqli_connect($this->host,$this->user,$this->pwd) or die("MySQL连接失败") ;
//        print_r($conn);die;
        mysqli_query($this->con,"set names 'utf8'");
        mysqli_select_db($this->con,$this->db_name);
//        print_r($return);die();
    }

    public function changeDB($db_name=''){
        $this->db_name=$db_name;
        return mysqli_query($this->con,'use '.$this->db_name);
    }

    public function field($field){
        if(empty($field)){
            $this->field=' * ';
        }else{
            $this->field=' '.$field.' ';
        }
        return $this;
    }
    /*1-key,2-value,3-condition*/
    public function where($where){
        $this->where=' where ';
        if(!empty($where)){
            if(is_array($where)){
                $i=0;
                $keys=array_keys($where);
                if($keys===array_keys($keys)){
                    foreach ($where as $k => $v){
                        if($i<=0){
                            $this->where.=' ('.$v[0].' '.$v[2].' '.$v[1].') ';
                        }else{
                            $this->where.=' and ('.$v[0].' '.$v[2].' '.$v[1].') ';
                        }
                        $i++;
                    }
                }else{
                    foreach ($where as $k => $v){
                        if($i<=0){
                            $this->where.=' (`'.$k.'` = \''.$v.'\') ';
                        }else{
                            $this->where.=' and (`'.$k.'` = \''.$v.'\') ';
                        }
                        $i++;
                    }
                }
            }else{
                $this->where.=$where.' ';
            }
        }
        return $this;
    }

    public function group($group){
        if(!empty($group)){
            $this->group=' group by '.$group.' ';
        }
        return $this;
    }

    public function order($order){
        if(!empty($order)){
            $this->order=' order by '.$order.' ';
        }
        return $this;
    }

    public function query($sql='',$type='select'){
        if($type=='select'){
			$res=mysqli_query($this->con,$sql);
			$data=[];
			while ($row=mysqli_fetch_assoc($res)) {
				$data[]=$row;
			}
		}else{
			$data=mysqli_query($this->con,$sql);
		}
        return $data;
    }

    public function M($tab=''){
        if(!empty($tab)){
            $this->tab=$tab;
        }
        return $this;
    }

    public function select(){
        if(empty($this->tab)){die('未指定数据表');}
        $sql='select '.$this->field.' from `'.$this->tab.'` '.$this->where.' '.$this->group.' '.$this->order;
        $res=mysqli_query($this->con,$sql);
        $data=[];
        while ($row=mysqli_fetch_assoc($res)) {
            $data[]=$row;
        }
		$this->field='*';
		$this->group='';
		$this->order='';
		$this->where='';
		$this->tab='';
        return $data;
    }
	
	public function find(){
		if(empty($this->tab)){die('未指定数据表');}
        $sql='select '.$this->field.' from '.$this->tab.' '.$this->where.' '.$this->group.' '.$this->order.' limit 0,1';
        $res=mysqli_query($this->con,$sql);
        $data=@mysqli_fetch_assoc($res);
		$this->field='*';
		$this->group='';
		$this->order='';
		$this->where='';
		$this->tab='';
        return $data;
	}
	
	public function add($data){
		if(empty($this->tab)){die('未指定数据表');}
		$key=[];
		$val=[];
		foreach($data as $k => $v){
			$key[]='`'.$k.'`';
			$val[]='\''.$v.'\'';
		}
		$sql='INSERT INTO `'.$this->tab.'` ('.implode(',',$key).') VALUES ('.implode(',',$val).');';
		$res=mysqli_query($this->con,$sql);
		return $res;
	}
	
	public function addAll($data){
		if(empty($this->tab)){die('未指定数据表');}
		$val=[];
		$key=[];
		$flag=1;
		if(empty($data)){
			return false;
		}else{
			foreach($data as $k => $v){
				$value=[];
				foreach($v as $ke => $va){
					if($flag==1){
						$key[]='`'.$ke.'`';
					}
					$value[]=$va;
				}
				$val[]='('.implode(',',$value).')';
				$flag++;
			}
		}
		$sql='INSERT INTO `'.$this->tab.'` ('.implode(',',$key).') VALUES '.implode(',',$val).';';
		$res=mysqli_query($this->con,$sql);
		return $res;
	}
}

function mt4_operation($request){
    $server = "103.14.78.198";
    $port = 1950;
    $socketPtr = fsockopen($server, $port, $errno, $errstr, 0.4);
    fputs($socketPtr, $request);
    $size = fgets($socketPtr, 64);
    $answer = "";
    $readed = 0;
    while($readed < $size){
        $part = fread($socketPtr, $size - $readed);
        $readed += strlen($part);
        $answer .= $part;
    }
    fclose($socketPtr);
    return $answer;
}

$min=10180;$max=52300;
$model=new db_connect('localhost','mansing','root','Mansing@SQL9340');
$date=strtotime(date('Y-m-d'));
$hasSet=$model->M('set_balance_log')->where(['date'=>$date])->find();
if(empty($hasSet)){
    $model->changeDB('mt4');
//    $list=$model->M('mt4_users')->field('LOGIN,BALANCE')->select();
    $list=$model->query('select LOGIN,BALANCE from mt4_users where (LOGIN between '.$min.' and '.$max.') and (BALANCE > 0)','select');
    $filename=date('Ymd-His');
    if(count($list)){//判断是否有符合条件的用户
        $model->changeDB('mansing');
        $rate=$model->M('into_gold_set')->field('rate')->where(['type'=>2,'state'=>1])->find();
        if(empty($rate)){
            $data['msg']='没有设置利息比例';
            $filename.='-no set.txt';
        }else{
            $log=[];
            foreach ($list as $k =>$v){
                $money=$v['BALANCE']*$rate['rate'];
                $request = "action=changebalance&login=".$v['LOGIN']."&value=".$money."&comment=balance#profit ".date('Y-m-d')."\0";//bulkchangebalance-批量修改bulk
                $return=mt4_operation($request);
                parse_str($return,$res);
                $log[]=array(
                    'user_id'=>$v['LOGIN'],
                    'balance'=>$v['BALANCE'],
                    'profit'=>$money,
                    'rate'=>$rate['rate'],
                    'date'=>'\''.date('Y-m-d').'\'',
                    'time'=>time(),
                    'status'=>$res['result']
                );
            }
            $model->M('profit')->addAll($log);

            $data['msg']='操作成功';
            $data['data']=$log;
            $filename.="-success.log";
            $setlog['uid']=0;//操作人
            $setlog['date']=$date;//操作日期
            //$setlog['type']=2;//
            $setlog['time']=time();//时间
            $model->M('set_balance_log')->add($setlog);
        }
    }else{
        $data['msg']='没有需要发放利息的数据';
        $filename.='-no data.txt';
    }
    $data=var_export($data,true);
    file_put_contents('C:/phpStudy/WWW/YuH/Uploads/setBalanceLog/'.$filename,$data);
}
?>